<template>
  <div class="bank-page">
    <nav-bar title="题库练习" theme="blue" message></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-tabs v-model="activeName" @change="getQuestionList(1)">
          <van-tab title="智能刷题" name="subject"></van-tab>
          <van-tab title="我的错题" name="wrongSubject">
            <div class="exam-wrong">
              <div class="exam-wrong-total van-hairline--bottom">
                <van-row :gutter="8">
                  <van-col span="12" align="center">
                    <div class="exam-wrong-con">
                      <span class="exam-wrong-con-icon">
                        <van-icon name="cross" />
                      </span>
                      <span class="exam-wrong-con-text">今日错题</span>
                      <span class="exam-wrong-con-num color-orange">{{ todayCount }}</span>
                    </div>
                  </van-col>
                  <van-col span="12" align="center">
                    <div class="exam-wrong-con">
                      <span class="exam-wrong-con-icon">
                        <van-icon name="underway-o" />
                      </span>
                      <span class="exam-wrong-con-text">历史错题</span>
                      <span class="exam-wrong-con-num color-red">{{ historyCount }}</span>
                    </div>
                  </van-col>
                </van-row>
              </div>
              <div class="exam-wrong-switch">
                <van-field name="switch" label="错题答对移除" input-align="right" :label-width="120">
                  <template #input>
                    <van-switch v-model="isRemoveWrongQuestion" size="24" />
                  </template>
                </van-field>
              </div>
            </div>
          </van-tab>
        </van-tabs>
        <!-- 课程类型 -->
        <template v-if="courseTypeList.length">
          <van-tabs v-model="subjectTypeCode" line-height="0" swipe-threshold="3" @click="getQuestionList(1)">
            <van-tab
              v-for="item in courseTypeList"
              :key="item.subjectTypeCode"
              :title="item.subjectType"
              :name="item.subjectTypeCode"
            >
              <template #title>
                <van-tag
                  v-if="questionParams.subjectTypeCode === item.subjectTypeCode"
                  type="primary"
                  round
                  plain
                  size="large"
                  style="background-color: rgba(60, 189, 208, 0.1)"
                >
                  {{ item.subjectType }}
                </van-tag>
                <van-tag v-else round size="large" text-color="rgba(0, 0, 0, 0.78)" color="#f6f6f6">
                  {{ item.subjectType }}
                </van-tag>
              </template>
            </van-tab>
          </van-tabs>
        </template>
        <!-- 题目 -->
        <div class="exam-initiateexam-box">
          <van-swipe ref="swipe" :stop-propagation="false" :show-indicators="false" @change="handleSwipeChange">
            <van-swipe-item v-for="(item, index) in questionList" :key="index">
              <div class="exam-initiateexam-box-swipename">
                <p class="exam-initiateexam-box-swipename-left">
                  {{ item.typeCodeName }}
                  <span v-if="item.myVersion && item.myVersion !== item.version">（该题已修改，请重新作答）</span>
                </p>
              </div>
              <div class="exam-initiateexam-box-content">
                <div class="exam-initiateexam-box-content-title">{{ index + 1 + '、' }}{{ item.title }}</div>
                <template v-if="item.typeCode === '1'">
                  <div
                    v-for="(optionItem, optionIndex) in item.option"
                    :key="optionIndex"
                    class="exam-initiateexam-box-content-option"
                    @click.stop="myAnswer = optionItem.itemName"
                  >
                    <p
                      class="title-num"
                      :class="{
                        checked: myAnswer === optionItem.itemName
                      }"
                    >
                      {{ optionItem.itemName }}
                    </p>
                    <p class="title-text">{{ optionItem.item }}</p>
                  </div>
                </template>
                <template v-if="item.typeCode === '2'">
                  <div
                    v-for="(optionItem, optionIndex) in item.option"
                    :key="optionIndex"
                    class="exam-initiateexam-box-content-option"
                    @click.stop="multipleChoose(item, optionItem)"
                  >
                    <p
                      class="title-num"
                      :class="{
                        checked: myAnswer.indexOf(optionItem.itemName) !== -1
                      }"
                    >
                      {{ optionItem.itemName }}
                    </p>
                    <p class="title-text">{{ optionItem.item }}</p>
                  </div>
                </template>
                <template v-if="item.typeCode === '3'">
                  <van-field
                    v-model="myAnswer"
                    placeholder="请输入答案"
                    rows="5"
                    autosize
                    type="textarea"
                    show-word-limit
                    :border="false"
                    class="van-field__value--textarea"
                    maxlength="500"
                  />
                </template>
              </div>
              <div class="exam-analysis" v-if="isShowAnswer">
                <p class="exam-analysis-answer">
                  参考答案：
                  <span class="color-blue">
                    {{ item.answer }}
                  </span>
                </p>
                <p class="exam-analysis-content">解析：{{ item.analysis }}</p>
              </div>
            </van-swipe-item>
          </van-swipe>
          <van-empty
            :image="require('@/assets/images/basic/pic_no_content_color.png')"
            description="暂无内容~"
            style="height: 300px"
            v-show="!questionList.length"
          />
        </div>
      </van-sticky>
      <div class="answer-sheet" v-show="!isShowAnswer && questionList.length">
        <div class="answer-sheet-answer-center">
          <van-tag type="primary" @click="handleViewAnswer">查看答案</van-tag>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import LearnTest from '@/api/learnTest'
export default {
  data() {
    return {
      // 切换
      activeName: 'subject',
      // 获取题目参数
      subjectTypeCode: '',
      questionParams: {
        subjectTypeCode: '',
        pageNumber: 1,
        recordSize: 0,
        pageSize: 100,
        total: 0
      },
      // 课程类型
      courseTypeList: [],
      // 题目列表
      questionList: [],
      // 是否展示答案
      isShowAnswer: false,
      // 当前题目索引
      curQuestionIndex: 0,
      // 我的答案
      myAnswer: '',
      myAnswer_: [],
      // 今日错题
      todayCount: '',
      // 历史错题
      historyCount: '',
      // 开启错题答对移除
      isRemoveWrongQuestion: false
    }
  },
  created() {
    this.getCourseType()
    this.getQuestionList()
    this.getWrongCount()
  },
  methods: {
    // 获取课程类型
    getCourseType() {
      LearnTest.Course.typeList().then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.courseTypeList = data
        }
      })
    },
    // 获取题目
    getQuestionList(page) {
      // 数据初始化
      this.resetData()
      // 分页
      if (page) {
        this.questionParams.pageNumber = page
        this.questionList = []
      }
      const list = this.activeName === 'subject' ? 'list' : 'errorList'
      this.questionParams.subjectTypeCode = this.subjectTypeCode
      this.questionParams.recordSize = this.questionParams.pageSize * (this.questionParams.pageNumber - 1)
      LearnTest.QuestionBank[list](this.questionParams).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.questionList.push(...data.list)
          this.questionParams.total = data.count
          if (this.questionParams.recordSize > 0) {
            this.$nextTick(() => {
              // 跳转到下一页第一个
              this.$refs.swipe.swipeTo(this.questionParams.recordSize - 1, { immediate: true })
            })
          }
        }
      })
    },
    // 获取错题数量
    getWrongCount() {
      LearnTest.QuestionBank.count().then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.todayCount = data.todayCount
          this.historyCount = data.historyCount
        }
      })
    },
    // 多选题答案
    multipleChoose(item, optionItem) {
      if (this.myAnswer_) {
        if (this.myAnswer_.includes(optionItem.itemName)) {
          const index = this.myAnswer_.findIndex(o => o === optionItem.itemName)
          if (index > -1) this.myAnswer_.splice(index, 1)
        } else {
          this.myAnswer_.push(optionItem.itemName)
        }
      } else {
        this.myAnswer_ = [optionItem.itemName]
      }
      const answerOptions = item.option.filter(o => this.myAnswer_.includes(o.itemName))
      this.myAnswer = answerOptions.map(o => o.itemName).join('')
    },
    // 题目切换
    handleSwipeChange(index) {
      // 往右滑
      if (index > this.curQuestionIndex && !this.isShowAnswer) this.saveWrongQuestion()
      this.curQuestionIndex = index

      // 数据初始化
      this.resetData()

      // 分页
      if (
        index === this.questionList.length - 1 &&
        Math.ceil(this.questionParams.total / this.questionParams.pageSize) !== this.questionParams.pageNumber
      ) {
        this.questionParams.pageNumber++
        this.getQuestionList()
      }
    },
    // 查看答案
    handleViewAnswer() {
      this.isShowAnswer = true
      this.saveWrongQuestion()
    },
    // 错题保存
    async saveWrongQuestion() {
      const item = this.questionList[this.curQuestionIndex]
      if (this.myAnswer) {
        const isCorrectRemove = this.isRemoveWrongQuestion && this.activeName === 'wrongSubject' ? '1' : '0'
        // 保存用户答案
        const res = await LearnTest.QuestionBank.save({
          answer: this.myAnswer,
          questionCode: item.code,
          version: item.version,
          isErrorListSave: isCorrectRemove
        })
        const { status } = res.data
        // 答对移除
        if (status === 0 && isCorrectRemove === '1') {
          this.questionList.splice(this.curQuestionIndex, 1)
          this.getWrongCount()
          if (!this.questionList.length) {
            this.$dialog
              .confirm({
                title: '提示',
                message: '全部错题已答完，是否参与智能刷题',
                confirmButtonText: '是',
                cancelButtonText: '否'
              })
              .then(() => {
                this.activeName = 'subject'
                this.getQuestionList(1)
              })
          }
        }
      }
    },
    // 数据初始化
    resetData() {
      this.isShowAnswer = false
      this.myAnswer = ''
      this.myAnswer_ = []
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/learnTest/exam/question.less';
</style>
